package com.ctshk.rpc.bus.service.impl;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ctshk.common.utils.EntityUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.service.support.BaseService;
import com.ctshk.rpc.bus.dto.BusPriceRemainderDTO;
import com.ctshk.rpc.bus.dto.BusProductCostPriceDTO;
import com.ctshk.rpc.bus.dto.BusProductCostPriceFullInfoDTO;
import com.ctshk.rpc.bus.dto.BusProductStrategyDTO;
import com.ctshk.rpc.bus.dto.Constants;
import com.ctshk.rpc.bus.entity.BusProduct;
import com.ctshk.rpc.bus.entity.BusProductChannelOfflineSelfCustom;
import com.ctshk.rpc.bus.entity.BusProductCostPrice;
import com.ctshk.rpc.bus.entity.BusProductIncreaseStrategyRule;
import com.ctshk.rpc.bus.mapper.BusInitializationSettingsMapper;
import com.ctshk.rpc.bus.mapper.BusProductChannelOfflineSelfCustomMapper;
import com.ctshk.rpc.bus.mapper.BusProductCostMapper;
import com.ctshk.rpc.bus.mapper.BusProductCostPriceMapper;
import com.ctshk.rpc.bus.mapper.BusProductIncreaseStrategyRuleMapper;
import com.ctshk.rpc.bus.mapper.BusProductMapper;
import com.ctshk.rpc.bus.mapper.BusProductStrategyMapper;
import com.ctshk.rpc.bus.service.IBusProductCostPriceService;
import com.ctshk.rpc.system.dto.SysDepartmentDTO;
import com.ctshk.rpc.system.service.ISysDepartmentService;

/**
 * <p>
 * 巴士成本价格表 服务实现类
 * </p>
 *
 * @author 彭柳霖
 * @since 2021-02-19
 */
@DubboService
public class BusProductCostPriceServiceImpl extends ServiceImpl<BusProductCostPriceMapper, BusProductCostPrice> implements IBusProductCostPriceService, BaseService {


    @Autowired
    private BusProductCostMapper busProductCostMapper;
    @Autowired
    private BusProductMapper busProductMapper;
    @Autowired
    private BusProductStrategyMapper busProductStrategyMapper;
    @Autowired
    private BusProductIncreaseStrategyRuleMapper ruleMapper;
    @Autowired
    private BusProductChannelOfflineSelfCustomMapper busProductChannelOfflineSelfCustomMapper;
    @DubboReference
    private ISysDepartmentService sysDepartmentService;
    @Autowired
    private BusInitializationSettingsMapper busInitializationSettingsMapper;

    @Override
    public List<BusProductCostPriceDTO> queryPrice(Long busProductId, LocalDate queryDate) {
        List<BusProductCostPriceDTO> busProductCostPriceDTOList = busProductCostMapper.queryPrice(busProductId, queryDate);
        return busProductCostPriceDTOList;
    }

    /**
     * 根据巴士产品id和用户id，查询用户自营下的加幅后价格
     *
     * @param busProductId
     * @param userId
     * @return
     */
    @Override
    public BusPriceRemainderDTO selectSelfPriceRemainderAndLock(Long busProductId, Long userId) {

        BusPriceRemainderDTO busPriceRemainderDTO = new BusPriceRemainderDTO();
        LocalDate nowDate = LocalDate.now();
        BusProductIncreaseStrategyRule strategyRule = null;
        Integer remainderNumber = null;
        BusProduct busProduct = busProductMapper.selectById(busProductId);
        BusProductStrategyDTO busProductStrategy = busProductStrategyMapper.queryBusProductStrategyInfo(busProductId, nowDate);
        if (busProductStrategy != null) {
            // 代理禁售
            if (busProductStrategy.getAgentSalePermissionType() == Constants.SALE_CHANNEL_TYPE_DISABLED) {
                return null;
            } else if (busProductStrategy.getSelfSalePermissionType() == Constants.SALE_CHANNEL_TYPE_ALL) {
                //当前巴士-线下自营所有-获取加幅规则
                strategyRule = ruleMapper.selectById(busProductStrategy.getSelfSalePermissionId());

            } else if (busProductStrategy.getSelfSalePermissionType() == Constants.SALE_CHANNEL_TYPE_SELECTED) {
                //当前巴士-线下自营选中-获取加幅规则
                QueryWrapper<BusProductChannelOfflineSelfCustom> offlineSelfQueryWrapper = new QueryWrapper<>();
                offlineSelfQueryWrapper.lambda().eq(BusProductChannelOfflineSelfCustom::getRelationId, userId);
                offlineSelfQueryWrapper.lambda().eq(BusProductChannelOfflineSelfCustom::getIncreaseStrategyId, busProductStrategy.getId());
                BusProductChannelOfflineSelfCustom offlineSelfCustom = busProductChannelOfflineSelfCustomMapper.selectOne(offlineSelfQueryWrapper);
                if (offlineSelfCustom != null) {
                    // 当前机场快线-线下自营选中-查询加幅规则
                    QueryWrapper<BusProductIncreaseStrategyRule> ruleQueryWrapper = new QueryWrapper<>();
                    ruleQueryWrapper.lambda().eq(BusProductIncreaseStrategyRule::getCustomId, offlineSelfCustom.getId());
                    strategyRule = ruleMapper.selectOne(ruleQueryWrapper);

                } else {
                    SysDepartmentDTO sysDepartmentDTO = sysDepartmentService.queryByUserId(userId);
                    offlineSelfCustom = findParentDepartmentId(sysDepartmentDTO, busProductStrategy.getId());
                    if (offlineSelfCustom != null) {
                        // 当前机场快线-线下自营选中-查询加幅规则
                        QueryWrapper<BusProductIncreaseStrategyRule> ruleQueryWrapper = new QueryWrapper<>();
                        ruleQueryWrapper.lambda().eq(BusProductIncreaseStrategyRule::getCustomId, offlineSelfCustom.getId());
                        strategyRule = ruleMapper.selectOne(ruleQueryWrapper);

                    }
                }
            }
        }
        BigDecimal primeAdultPrice = BigDecimal.ZERO;
        BigDecimal primeChildPrice = BigDecimal.ZERO;

        List<BusProductCostPriceDTO> priceDTOList = busProductCostMapper.queryPrice(busProduct.getId(), LocalDate.now());
        if (!CollectionUtils.isEmpty(priceDTOList)) {
            for (BusProductCostPriceDTO priceDTO : priceDTOList) {
                if (priceDTO.getPassengerId() == 1) {
                    primeAdultPrice = priceDTO.getPrice();
                } else if (priceDTO.getPassengerId() == 2) {
                    primeChildPrice = priceDTO.getPrice();
                }
            }
        }
        // 巴士-加幅
        if (strategyRule == null) {
            busPriceRemainderDTO.setAdultPrice(primeAdultPrice);
            busPriceRemainderDTO.setChildrenPrice(primeChildPrice);
        } else {
            Integer adultPriceType = strategyRule.getPriceType();
            BigDecimal adultPrice = strategyRule.getPrice();

            Integer childPriceType = strategyRule.getPriceType();
            BigDecimal childPrice = strategyRule.getPrice();
            if (adultPriceType == 1) { //加数值
                primeAdultPrice = primeAdultPrice.add(adultPrice);
            } else if (adultPriceType == 2) {
                //加百分比
                primeAdultPrice = primeAdultPrice.add(primeAdultPrice.multiply(adultPrice));
            }

            if (childPriceType == 1) { //加数值
                primeChildPrice = primeChildPrice.add(childPrice);
            } else if (childPriceType == 2) {
                //加百分比
                primeChildPrice = primeChildPrice.add(primeChildPrice.multiply(childPrice));
            }
            busPriceRemainderDTO.setAdultPrice(primeAdultPrice);
            busPriceRemainderDTO.setChildrenPrice(primeChildPrice);
        }


        return busPriceRemainderDTO;
    }

    /**
     * 查询产品价格完整信息列表
     *
     * @param productId
     * @return
     */
    @Override
    public List<BusProductCostPriceFullInfoDTO> queryFullInfoList(Long productId, LocalDate departureDate) {
        validateNotNull(productId, departureDate);
        return getBaseMapper().queryFullInfoList(productId, departureDate);
    }

    @Override
    public List<BusProductCostPriceDTO> findBusCostPriceList(List<Long> costIds) {
        //
        if(costIds == null || costIds.size() <= 0){
            return new ArrayList<BusProductCostPriceDTO>();
        }
        LambdaQueryWrapper<BusProductCostPrice> wrapper = Wrappers.<BusProductCostPrice>lambdaQuery().in(BusProductCostPrice::getCostId, costIds);
        List<BusProductCostPrice> busProductCostPrices = baseMapper.selectList(wrapper);
        return EntityUtil.copyList(busProductCostPrices, BusProductCostPriceDTO.class);
    }


    /**
     * 根据部门信息，递归查询加幅策略-线下自营信息
     *
     * @param sysDepartmentDTO   部门信息
     * @param increaseStrategyId 加幅策略id
     * @return 加幅策略-线下自营信息
     */
    private BusProductChannelOfflineSelfCustom findParentDepartmentId(SysDepartmentDTO sysDepartmentDTO, Long increaseStrategyId) {
        QueryWrapper<BusProductChannelOfflineSelfCustom> offlineSelfQueryWrapper = new QueryWrapper<>();
        offlineSelfQueryWrapper.eq("relation_id", sysDepartmentDTO.getId());
        offlineSelfQueryWrapper.lambda().eq(BusProductChannelOfflineSelfCustom::getIncreaseStrategyId, increaseStrategyId);
        BusProductChannelOfflineSelfCustom busProductChannelOfflineSelfCustom = busProductChannelOfflineSelfCustomMapper.selectOne(offlineSelfQueryWrapper);
        if (busProductChannelOfflineSelfCustom == null && sysDepartmentDTO.getParentId() != null) {
            // 查找上級部門
            SysDepartmentDTO sysDepartmentDTOTemp = sysDepartmentService.queryOne(sysDepartmentDTO.getParentId());
            if (sysDepartmentDTOTemp == null) {
                return null; //没有上级部门，返回null
            }
            busProductChannelOfflineSelfCustom = findParentDepartmentId(sysDepartmentDTOTemp, increaseStrategyId);

        }
        return busProductChannelOfflineSelfCustom;
    }
}
